class Snake {
    // 蛇头
    head:HTMLElement;
    // 身体
    bodies:HTMLCollection;
    // 蛇的容器
    element: HTMLElement;
    constructor() {
        this.element = document.getElementById('snake')!
        this.head = document.querySelector('#snake > div') as HTMLElement;
        this.bodies = this.element.getElementsByTagName('div')
    }
    get X() {
        return this.head.offsetLeft
    }
    get Y() {
        return this.head.offsetTop
    }
    set X(value:number) {
        if(this.X === value) {
            return
        }
        if(value > 290 || value < 0){
            throw new Error('🐍撞墙了')
        }
        // 掉头处理
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value) {
            if(value >this.X){
                // 如果新值vatve 大于日位X，则说明蛇在向石走，此时发生掉头，应法使蛇然续向左走
                value = this.X -10
            }else {
                // 向左走
                value = this.X +10
            }
        }
        this.head.style.left = value + 'px'
        this.moveBody()
        // this.checkHeadBody()
    }
    set Y(value:number) {
        if(this.Y === value) {
            return
        }
        if(value > 290 || value < 0){
            throw new Error('🐍撞墙了')
        }
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value) {
            
            if(value >this.Y){
                // 如果新值vatve 大于日位X，则说明蛇在向石走，此时发生掉头，应法使蛇然续向左走
                value = this.Y -10
            }else {
                // 向左走
                value = this.Y +10
            }
        }
        this.head.style.top = value + 'px'
        this.moveBody()
        // this.checkHeadBody()
    }
    addBody() {
        // let nodep = document.createElement('div')
        // this.element.appendChild(nodep)
        this.element.insertAdjacentHTML("beforeend","<div></div>")
        
    }
    moveBody() {
        for(let i = this.bodies.length -1; i>0; i--){
            let X = (this.bodies[i-1] as HTMLElement).offsetLeft;
            let Y = (this.bodies[i-1] as HTMLElement).offsetTop;
            (this.bodies[i] as HTMLElement).style.left = X + 'px';
            (this.bodies[i] as HTMLElement).style.top = Y + 'px';
        }
    }
    checkHeadBody() {
        for(let i = 1; i<this.bodies.length; i++) {
            let bd = this.bodies[i] as HTMLElement
            if(this.X === bd.offsetLeft && bd.offsetTop) {
                throw new Error('撞到自己啦')
            }
        }
    }
}

export default Snake